package com.sctvcloud.dongqu.ui.activities;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomLinearLayout;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.application.Cache;
import com.sctvcloud.dongqu.base.BaseActivity;
import com.sctvcloud.dongqu.application.Constances;
import com.sctvcloud.dongqu.beans.ADynamicsItem;
import com.sctvcloud.dongqu.beans.AFileItem;
import com.sctvcloud.dongqu.beans.FUsers;
import com.sctvcloud.dongqu.beans.SingleResult;
import com.sctvcloud.dongqu.http.AbsListNetCallback;
import com.sctvcloud.dongqu.http.AbsNetCallBack;
import com.sctvcloud.dongqu.http.NetUtils;
import com.sctvcloud.dongqu.http.ParamsEditor;
import com.sctvcloud.dongqu.ui.adapter.AnchorHomePageAdapter;
import com.sctvcloud.dongqu.ui.adapter.holder.AnchorHomeDynamicsHolder;
import com.sctvcloud.dongqu.ui.utils.GPlayerBottomControllerImp;
import com.sctvcloud.dongqu.ui.utils.GSFPlayerScreenControllImp;
import com.sctvcloud.dongqu.ui.utils.SkipUtil;
import com.sctvcloud.dongqu.ui.utils.TitleUtils;
import com.sctvcloud.dongqu.utils.UserManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by yuxipan on 2018-01-16.
 * 主播动态列表
 */

public class AnchorDyListActivity extends BaseActivity implements CanRefreshLayout.OnRefreshListener
        , CanRefreshLayout.OnLoadMoreListener, CanRefreshLayout.IScrollView {
    @BindView(R.id.anchor_home_refreshLayout)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.anchor_home_page_ll)
    protected LinearLayout top_ll;
    @BindView(R.id.can_content_view)
    protected CustomLinearLayout detail;
    @BindView(R.id.anchor_home_page_list)
    protected RecyclerView recyclerView;
    private Handler handler;
    private String titleStr;
    private AnchorHomePageAdapter adapter;
    private LinearLayoutManager manager;
    private String homePageUrl;
    private GPlayerBottomControllerImp bottomController;
    private GSFPlayerScreenControllImp screenControllImp;
    private ADynamicsItem dynamicsTemp;
    protected String contentVideoUrl;
    private int tempPos;
    private int height;
    private int anchorType = 0;
    private int index = 0;
    private final static int pageSize = 10;
    private ArrayList<AFileItem> fileItems = new ArrayList<>();
    private boolean hasMore = false;
    private ArrayList<ADynamicsItem> dyDatas = new ArrayList<>();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        handler = new Handler();
        anchorType = getIntent().getIntExtra(EX_TYPE, 0);
        initViews();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_anchor_home_page);
        ButterKnife.bind(this);
    }

    private void initViews() {
        final int pa = getResources().getDimensionPixelOffset(R.dimen.divider_shadow_margin_bottom);
        top_ll.postDelayed(new Runnable() {
            @Override
            public void run() {
                height = top_ll.getHeight() + pa;
            }
        }, 300);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(manager);
        detail.setiScrollView(this);
        refreshLayout.autoRefresh();

    }

    @Override
    public void onLoadMore() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.loadMoreComplete();
        } else {
            index++;
//            getAnchorList();
            getTimeLineList();
        }
    }

    @Override
    public void onRefresh() {
        index = 0;
        getTimeLineList();
    }

    @Override
    public boolean canScrollUp(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(recyclerView, -1);
    }

    @Override
    public boolean canScrollDown(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(recyclerView, 1);
    }

    /**
     * 主播发布动态数据请求
     */
    private void getTimeLineList() {

        HashMap<String, Object> param = new HashMap<>();
        param.put("anchorId", "");
        param.put("capacity", pageSize);
        param.put("index", index);
        param.put("requestType", 1);
        param.put("siteNumber", Constances.SITE_ID);
        FUsers user = UserManager.getInstance().getUser();
        if (user != null && !TextUtils.isEmpty(user.getUserId())) {
            param.put("userId", user.getUserId());
        } else {
            param.put("userId", "");
        }
        NetUtils.getNetAdapter().getTimelineList(getOwnerName(), param, new AbsListNetCallback<ADynamicsItem>(ADynamicsItem.class) {
            @Override
            public void onSuc(List<ADynamicsItem> anchortimelines) {
                if (dyDatas == null) {
                    dyDatas = new ArrayList<>();
                }
                if (index == 0) {
                    dyDatas.clear();
                }
                if (ListUtils.isListValued(anchortimelines)) {
                    dyDatas.addAll(anchortimelines);
                    if (anchortimelines.size() >= pageSize) {
                        hasMore = true;
                    } else {
                        hasMore = false;
                    }
                }
                if (adapter == null) {
                    adapter = new AnchorHomePageAdapter(AnchorDyListActivity.this, dyDatas);
                    adapter.setPlayClick(playClick);
                    recyclerView.setAdapter(adapter);
                } else {
                    adapter.setData(dyDatas);
                }

            }

            @Override
            public List<ADynamicsItem> doInBackground(List<ADynamicsItem> aDynamicsItems) {
                if (aDynamicsItems != null) {
                    for (ADynamicsItem item : aDynamicsItems) {
                        item.setViewType(AnchorHomePageAdapter.VIEWTYPE_DYNAMICS);
                    }
                }

                return super.doInBackground(aDynamicsItems);
            }

            @Override
            public void onEnd() {
                onNetFinish();
                super.onEnd();
            }
        });


    }

    private void getAnchorList() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("count", pageSize);
        param.put("index", index);
        param.put("requestType", anchorType);
        param.put("siteNumber", Constances.SITE_ID);
        NetUtils.getNetAdapter().getRadioHostDoc(getOwnerName(), param, new AbsListNetCallback<AFileItem>(AFileItem.class) {
            @Override
            public void onSuc(List<AFileItem> aFileItems) {

                if (ListUtils.isListValued(aFileItems)) {
                    if (index == 0) {
                        fileItems.clear();
                    }
                    fileItems.addAll(aFileItems);
                }


                if (aFileItems.size() >= pageSize) {
                    hasMore = true;
                } else {
                    hasMore = false;
                }
                if (adapter == null) {
                    adapter = new AnchorHomePageAdapter(AnchorDyListActivity.this, fileItems);
                    adapter.setPlayClick(playClick);
                    adapter.setInAnchorDetail(true);
                    recyclerView.setAdapter(adapter);
                } else {
                    adapter.setData(fileItems);
                }
            }

            @Override
            public List<AFileItem> doInBackground(List<AFileItem> aFileItems) {

                if (aFileItems != null) {
                    for (AFileItem item : aFileItems) {
                        item.setViewType(AnchorHomePageAdapter.VIEWTYPE_HOME_FILE);
                    }
                }
                return super.doInBackground(aFileItems);
            }

            @Override
            public void onEnd() {
                onNetFinish();
                super.onEnd();
            }
        });

    }

    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
        if (refreshLayout.isLoading()) {
            refreshLayout.loadMoreComplete();
        }
        refreshLayout.setLoadMoreEnabled(hasMore);
    }

    OnItemInternalClick playClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            switch (view.getId()) {
                case R.id.item_anchor_home_dynamics_video_play:
                    ADynamicsItem dynamics = (ADynamicsItem) adapter.getItem(position);
                    contentVideoUrl = UrlUtils.linkUrls(Constances.ST_BASE_URL, dynamics.getContentVideo());
                    SkipUtil.skipToVideoPlay(AnchorDyListActivity.this, contentVideoUrl, dynamics.getPlayedPos(), position);
                    break;
                case R.id.tv_anchor_up:
                    if (!UserManager.isLoginS()) {
                        toLogin();
                        return;
                    }
                    ADynamicsItem dyUp = (ADynamicsItem) adapter.getItem(position);
//                    if (dyUp.getAttitudesStatus()) {
//                        toast("已经点过赞啦");
//                        return;
//                    }
                    doUp(dyUp, position);
                    break;
                case R.id.tv_anchor_comment:
                    ADynamicsItem adi = (ADynamicsItem) adapter.getItem(position);
                    Intent intent = new Intent(AnchorDyListActivity.this, CommentDetailActivity.class);
                    intent.putExtra(EX_DATA, adi);
                    intent.putExtra(EX_COMMENT_TYPE, 3);
                    startActivity(intent);
                    break;
            }
        }


    };
    private AnchorHomeDynamicsHolder lastHolder = null;
    private void doUp(final ADynamicsItem aDynamicsItem, int position) {
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        View lastView = manager.findViewByPosition(position);

        if (null != lastView && recyclerView.getChildViewHolder(lastView) instanceof AnchorHomeDynamicsHolder) {
            lastHolder = (AnchorHomeDynamicsHolder) recyclerView.getChildViewHolder(lastView);
            if (null != lastHolder) {
                lastHolder.getTvUp().setDrawableEnlarge();
            }
        }
        ParamsEditor pe = new ParamsEditor();
//        HashMap<String, Object> param = new HashMap<>();
        pe.put("dynamicId", aDynamicsItem.getDynamicId());
//        pe.put("token", UserManager.getInstance().getToken());
        pe.put("userId", UserManager.getInstance().getUser().getUserId());
        pe.put("fType", 1);//1 主播 2报料 3新闻(短视频) 4 直播
        NetUtils.getNetAdapter().doUpForDynamics(getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsNetCallBack<SingleResult>(SingleResult.class) {
            @Override
            public void onSuc(SingleResult singleResult) {
                if (singleResult.isSuccess()) {
                    SkipUtil.skipToAddUserOperate(AnchorDyListActivity.this, getOwnerName(), 13, 2, "主播圈点赞", aDynamicsItem.getDynamicId(), Cache.getInstance().getCurrentChannelId());
                    for (ADynamicsItem item : dyDatas) {
                        if (item.getDynamicId().equals(aDynamicsItem.getDynamicId())) {
                            item.setAttitudesCount(aDynamicsItem.getAttitudesStatus() ? aDynamicsItem.getAttitudesCount() - 1 : aDynamicsItem.getAttitudesCount() + 1);
                            item.setAttitudesStatus(!aDynamicsItem.getAttitudesStatus());
                            adapter.notifyDataSetChanged();
                            if (item.getAttitudesStatus()) {
                                addInvitation(Constances.ADD_INTEGRAL_DOUP, false);
                            }
                        }
                    }
                }
            }
        });
    }


}
